<template>
	<div>
		<view class="pBox" v-show="showStatus" :style="{'overflow-y':showTask==true?'none':'auto','background':setData.bgcolor}">
			<view class="container" >
				<view class="header_box" :style="{'background':'url('+setData.banner+')',}">
					<view class="btn"  @click="next(0)"> </view>
					<view class="btn sort" @click="next(2)"> </view>
					<view class="complain" @click="next(3)"> 
						投诉
					</view>
					
					<view class="banner_bg" v-if="setData.show_winner && activityText.winners.length>0">
						<view class="name_banner" id="banner" :style="[{'animation-duration':bannerDelay,'width':bannerWidth+'px'}]">
							<view class="item" :class="{'banner_item':true}" v-for="(item,index) in activityText.winners" :key="index">
								<view class="avatr" >
									<image :src="item.avatar"   @error="imageError($event, index)"/>
								</view>
								<span>{{item.message}}</span>
							</view>
						</view>
					</view>
				</view>
				
				<view class="content_box">
					<view class="top_people">
						<span>已经有</span><div class="num_box"><span class="num" v-for="item in activityOtherData.text">{{item}}</span></div><span>人集齐</span>
					</view>
					<view class="info_container">
						<view class="stoptime">
							活动结束：<span class="time">{{timeData.day}}</span>天&nbsp;<span class="time">{{timeData.hours}}</span>:<span class="time">{{timeData.minutes}}</span>:<span class="time">{{timeData.second}}</span>
						</view>
						<!-- <view class="title">
							{{data.title}}
						</view> -->
						<div class="title_container">
							<div class="text_content">{{ data.title }}</div>
						</div>
						<view class="date">
							活动时间：{{settime(data.start_time)}}-{{settime(data.expire_time)}}
						</view>
						<view class="actdata" v-if="setData.show_data">
							<span>{{activityText.view_num}}浏览量</span>
							<span>{{activityText.play_num}}参与数</span>
						</view>
						<view class="progress" v-if="setData.show_prize && activityOtherData.total>0">
							<div class="text"><span>已领<span class="num">{{activityOtherData.total-activityOtherData.be_left}}份</span></span>/共{{activityOtherData.total}}份</div>
							<progress class="progress-d" :active="true" active-mode="forwards" :duration="10" activeColor="#FF7A59" backgroundColor="#FFC1B2" :percent="activityOtherData.progress" stroke-width="4" />
						</view>
						<view :class="{'card-list-8':wordLength<=8,'card-list-10':wordLength>8}">
							<view class="card" v-for="item in wordData" :style="{ 'background':'url('+item.image+') center center no-repeat','background-size': 'cover','filter':item.user_num==0?'grayscale(100%)':'grayscale(0%)'}">
								<view class="num" v-if="item.user_num>1">
									{{item.user_num}}
								</view>
							</view>
						</view>
						<view class="btn" @click="getpreWord">
							点我抽卡x <span>{{chance}}</span>
						</view>
					</view>
					<view style="margin: 30rpx 0 -20rpx;" v-if="setData.service_open">
						<service></service>
					</view>
					
					<view style="margin-bottom: 43rpx;" v-for="(item,index) in 	rules" :key="index">
						<view class="info">
							<div class="logo">
								<view class="title">
									<span>{{item.title}}</span>
								</view>
								<div class="other"></div>
							</div>
							
							<view>
								 <view class="dec" v-html="item.content">{{item.content}}</view>
							 </view>
						</view>
					</view>
					<div class="sports_swiper" v-if="bottom_ads.length!=0 &&setData.bottom_ad_open==true">
						  <swiper class="swiper" circular :indicator-dots="false" :autoplay="true"  :current="0">
						    <swiper-item v-for="(item,index) in bottom_ads" >
						      <div class="swiper_content" @click="jumpNew(item.link)">
						        <image  v-if="checkType(item.image)=='image'" class="swiper_img" :mode="'scaleToFill'" :src="item.image"></image>
									  <video class="swiper_video" v-if="checkType(item.image)=='video'" :src="item.image" :enable-progress-gesture="false" controls>
										</video>
						      </div>
						    </swiper-item>
						  </swiper>
					</div>
					<view class="footer_name" v-if="setData.copyright!=''">
						{{setData.copyright}}
					</view>
					<view v-else style="height: 40rpx;">
		
					</view>
				</view>
				
			</view>
			<view class="getMoreTimes" v-if="(activityText.has_task && taskMenuData.length>0) || isframe  ">
				<img :src="setData.task_float" @click="openTaskCenter"></img>
			</view>
			<taskCenter ref="taskcenter" @backNums="getNum" :act_type="'collect'" :show="showTask" :topImage="setData" :list="taskMenuData" @close="handlerCloseTaskCenter" @finish="handlerTaskFinish"></taskCenter>
			<advertise  :data="advSet" @close="closeAdv"></advertise>
			<share v-if="showShare" :data="data" @close="showShare=false"></share>
			<guide></guide>
			<help :data="setData" v-if="showHelpModal" @hideMissionModal="hideModal"></help>
			<collectPhone  :data="data" ></collectPhone>
			<view class="modal fadeIn" v-if="modalLott">
				<div class="container" v-if="lottData.hasOwnProperty('word')">
						<div class="topimage"></div>
						<view class="word" :style="{ 'background':'url('+lottData.word.image+') center center no-repeat'}"></view>
						<view class="btn" v-if="chance>0" @click="getWord(0)">
							点我抽卡×<span>{{chance}}</span>
						</view>
						<view class="btn" v-if="chance==0" @click="getWord(1)">
							获得更多抽卡机会
						</view>
						<view class="close" @click="modalLott=false"> </view>
				</div>
				<div class="prizeAnimation" v-if="lottData.hasOwnProperty('prize') && !isFinishAnimation" :style="{background: 'url('+qiniuUrl+'cards_all.png) center center no-repeat'}">
					<div class="cardlist">
						<div :class="{'card-list-8':wordLength<=8,'card-list-10':wordLength>8}">
							<div ref="finish_cards" style="opacity: 0;" class="card" v-for="(item,index) in wordData" :key="index" :style="{ 'background':'url('+item.image+') center center no-repeat','background-size': 'cover'}">
							</div>
						</div>
						<div class="hints_" ref="hints">奖品派发中···<br/>（请勿关闭页面）</div>
					</div>
				</div>
				<div class="container c1 fadeIn" v-if="lottData.hasOwnProperty('prize')  && isFinishAnimation">
						<div class="topimage"></div>
						<view class="word" :style="{ 'background':'url('+lottData.prize.image+') center center no-repeat'}"></view>
						<view class="title">
							{{lottData.prize.title}}
						</view>
						<view class="btn" @click="next(1)">
							 去核销
						</view>
						<view class="hint">
							所中奖品可在“中奖记录”中查看
						</view>
						<view class="close" @click="modalLott=false"> </view>
				</div>
		    </view>

		</view>
		
	</div>
	
</template>

<script>
	import {getGuess,ActivityInfo,chance,activityText,taskList,collectWord,collectLottery} from '@/api/api.js'
	import {mapGetters} from 'vuex'
	import {LoginApp,checkLogin,getSystemInfo,isWeiXin,isQianfan,checkPlatform,proxyShareFun,newJumpUrl,countNumCollect} from '@/until/QFH5.js'
	import {formatTime} from '@/until/tool.js'
	import watermarkOption from '@/until/water.js'
	import {checkHostOrImage} from '@/until/tool'
	import * as frameJs from '@/model/frameData'
	import help from "../../../components/taskCenter/help";
	
	export default{
		components: {help},
		computed:{
			...mapGetters(['loginInfo', 'qiniuUrl', 'guide', 'updateTask','showCollectPhone'])
		},
		data(){
			return{
				advSet:{},//控制广告
				bannerDelay:'20s',//文字公告
				bannerWidth:'0px',//文字公告
				pageStatus:-1,//页面状态(刮奖蒙层显示类别) 3：图片
				times:0,

				showDate:{},//展示日期
				showTask:false,//任务中心
				taskMenuData:[],//任务中心菜单
				chance:0,
				gType:'',//主题类型
				gShadow:'',//刮刮乐阴影
				guaData:{ type:'text', content:'还差一点，继续刮' ,resetGua:false},//刮刮乐内容

				modalData:{show:false,type:2},//中奖弹窗
				serviceData:{},//弹窗使用的所有信息 	中奖内容
				data:{ start_time:0 },//页面所有数据
				setData:{},//基础设置参数
				rules:[],//商家说明
				actid:1,//活动id
				activityText:{ view_num:0, winners:[] },//动态文本数据
				taskid:156,//任务id
				taskData:null,//任务list

				showTaskModal:false,//弹窗任务
				showShare:false,//分享
				noTimes:false,//无次数
				isMoreTask:false,//是否还有未完成的任务,
				isframe:false,//被后端引用
				frameData:{ data:{ settings:{ win_popup:"" } } },
				showStatus:false,//v-clovk
				
				showHelpModal:false,
				
				nextAnimation:false,
				taskChance:0,
				openMusic:false,
				
				bottom_ads:[],
				wordData:[],
				wordLength:0,
				lottData:{
					word:{image:''}
				},//抽中信息
				modalLott:false,
				// modalStatus:false,
				activityOtherData:{
					progress:0,
				},
				timeData:{
					day:0,
					hours:'00',
					minutes:'00',
					second:'00'
				},
				timer:null,

				isFinishAnimation:false
			}
		},
		methods:{
			startFinishAnimation(){
				let _t = this
				this.$nextTick(()=>{
					let refsArr = _t.$refs.finish_cards
					let deep = 2000/refsArr.length
					let sock = 0
					setTimeout(() => {
						_t.$refs.hints.style.opacity = '1'
						_t.$refs.hints.className="hints_ fadeIn"
					}, 800);
					let timer = setInterval(()=>{
						sock++
						_t.$refs.finish_cards[sock-1].style.opacity = '1'
						_t.$refs.finish_cards[sock-1].className="card fadeIn"
						if(sock == refsArr.length){
							clearInterval(timer)
							setTimeout(() => {
								_t.isFinishAnimation = true
							}, 2000);
						}
					},deep)
					console.log(refsArr)
				})
			
			},
			jumpNew(url){
			  if('' == url || undefined == url){
			    return;
			  }else{
			    window.open(url)
			  }
			
			},
			checkType(val){
			    return this.$checkType(val)
			},
			//禁止划动
			moveHandle(){},
			//图片错误
			checkHost(url){
				return checkHostOrImage(url)
			},
			//隐藏
			hideModal() {
			  this.showHelpModal = false
			},
			imageError(e, index){
				this.activityText.winners[index]['avatar'] = '/static/guess/avatar.png'
			},
			//格式化时间
			settime(val){
				return formatTime(val,'YYYY-MM-DD')
			},
			//关闭广告
			closeAdv(){
				this.advSet.start_ad_show = false
				this.advSet.popup_ad_show = false
			},
			//
			login(){
				if(this.checkPlat()){
					LoginApp(this.actid)
				}
			},
			startTime(val){
				let data = val
				let _this = this
				this.timer = setInterval(()=>{
					if(data<=0){ clearInterval(_this.timer) }
					data--;
					_this.timeData =_this.fTime(data)
				},1000)
			},
			fTime(time){
				  let day = Math.floor(time/86400)
				  let other = time % 86400
				  let hours = Math.floor(other/3600)
				  let minutes = Math.floor(other % 3600 /60)
				  let second = Math.floor(other %60 )
				  return {day:day,hours:this.fstr(hours),minutes:this.fstr(minutes),second:this.fstr(second)}
			},
			fstr(tr){
				if(tr>9)return tr
				else return '0'+tr
			},
			next(val){
				countNumCollect(this.actid)
				if(val==0){
					let callback=()=>{
						let url ='/plugin/pages/collect/prize?id='+this.actid
						this.$navigateTo({ url:url})
					}
					this.getAuth(callback,null,true)	
				}else if(val==1){
					let url = '/plugin/pages/collect/prizeInfo?pid='+this.lottData.rid
					this.$navigateTo({ url: url})
				}else if(val==2){
					this.showShare = true
				}else if(val==3){
					let callback=()=>{
						this.$navigateTo({url:'/plugin/pages/complain?id='+this.actid+'&type='+this.type+'&plugin='+this.$route.query.plugin})
					}
					this.getAuth(callback,null,true)	
				}
				
				
			},
			getNum(val){
			},
			//检查平台
			checkPlat(){
				let plat = checkPlatform()
				if(!plat){
					this.$store.dispatch('setGuideShow',4)
				}
				return plat
			},
			//所有前置条件
			async getAuth(callback=()=>{},back=()=>{},isNeglect=false){
				let {isWechat,phone} = this.guide
				if(this.checkPlat()){
					if(!isNeglect && this.pageStatus==0){
						uni.showToast({ title:'活动还没开始呢', icon:'none' })
						return
					}
					if(!isNeglect && this.pageStatus==1){
						uni.showToast({ title:'活动已经结束了', icon:'none' })
						return
					}
					let loginStatus = await checkLogin()
					if(!loginStatus){
						this.login()
						return
					}
					//收集信息
					if(this.data.collect==1 && this.showCollectPhone=='' && isWeiXin()){
						this.$store.commit('SET_SHOWCOLLECT',true)
						return
					}

					if(isQianfan()){
						if(!isWechat){
							this.$store.dispatch('setGuideShow',1)
							back()
							return
						}
						if(phone==""){
							this.$store.dispatch('setGuideShow',2)
							return
						}
						callback()
					}else{
						callback()
					}
				}
			},	
			
			//关闭任务
			handlerCloseTaskCenter(val){
				this.showTask = val
			},
			//完成任务
			handlerTaskFinish(val){
				if(val && val.type=='share')
					this.showShare = true
				this.initTask()
				this.getChance()
			},
			openTaskCenter(){
				countNumCollect(this.actid)
				let callback = ()=>{
					this.showTask = !this.showTask
				}
				this.getAuth(callback)
			},
			handlerCloseTask(){
				this.showTaskModal=false
				this.taskFinish()
				this.initTask()
				this.getChance()
			},
			async init(){
				let res = null
				let nowTime =  Math.floor(new Date()/1000)
				if(!this.isframe){
						res = await ActivityInfo({actid:this.actid})
				}else{
					res = this.frameData
				}
				if(res.code == 0){
					// #ifdef H5
					if(res.data.status==0){
						watermarkOption.set('活动未发布')
					}
					// #endif
					this.$setTitle(res.data.title)
					uni.setStorageSync('title',res.data.title)
					this.data = res.data
					let _this = this
					this.$nextTick(()=>{
						let token = localStorage.getItem(_this.actid+'bearerToken') || null
						if(token!=null && _this.$store.state.long==0 && _this.$store.state.lat==0  &&_this.data.area && _this.data.area.type==3){
							_this.$store.dispatch('getPos')
							window.getLocationCallBackFun=()=>{}
						}
					})
					uni.setStorageSync('collectData',res.data)
					let {settings} = res.data
					uni.setStorageSync('platform',JSON.stringify(settings.platform))
					this.setData =settings
					this.advSet = settings
					this.bottom_ads = settings.bottom_ads
 

					//规则排序
					this.rules = []
					settings.sort.forEach(item=>{
						if(res.data[item]){
							let obj = {title:this.formartText(item),content:res.data[item]}
							this.rules.push(obj)
						}
					})
					// this.gType = settings.guess_bg
					if(settings.layer_banner!=''){
						this.pageStatus = 3
					}
					this.$store.dispatch('serviceInfo',settings)
				}
				if(nowTime<res.data.start_time){
					this.pageStatus = 0
					this.times = res.data.start_time
					// this.startTime()
				}else if(nowTime>res.data.expire_time){
					this.pageStatus = 1
				}
				if(nowTime>res.data.start_time && nowTime<res.data.expire_time && res.data.expire_time-nowTime>0 ){
					this.startTime(res.data.expire_time-nowTime)
				}else{
					this.timeData={day:0,hours:'00',minutes:'00',second:'00'}
				}
				this.openMusic = res.data.settings.open_music
				this.$nextTick(() => {
					let data =  res.data
					proxyShareFun(data.settings.title,data.settings.image,data.settings.desc,window.location.href)
				})
 
				// this.$refs['taskcenter'].getCard()
			},
			formartText(val){
				let {business_intro,activity_rules,prize_intro} = this.setData.custom_desc_key
				switch(val){
					case 'business_intro':return business_intro!=''?business_intro:'商家介绍'
					case 'activity_rules':return activity_rules!=''?activity_rules:'活动规则'
					case 'prize_intro':return prize_intro!=''?prize_intro:'奖品介绍'
				}
			},
			formatImage(host,val){
				return host+val
			},
			//设置公告速度
			initCss(){
				let _this = this
				let width = 0
				uni.createSelectorQuery().in(this).selectAll(".banner_item").boundingClientRect(dom=>{
					if(dom.length>0){
						dom.forEach(item=>{ width += item.width })
						uni.getSystemInfo({
							success(res) {
								let pix = res.windowWidth/750
								//10右边间距
								_this.bannerWidth=width+pix*10*(dom.length-1)
								let pixWidth = 750  //*pix
								let nWidth = _this.bannerWidth>pixWidth?_this.bannerWidth:pixWidth
								_this.bannerDelay = parseInt(nWidth/30)+"s"
							}
						})
					}
				}).exec();
			},

			//获取刮奖次数
			getChance(){
				chance({actid:this.actid}).then(res=>{
					this.chance = res.data.num || 0
				})
			},
			//获取动态文本
			getActivity(){
				// console.log('发起请求',this.actid)
				activityText({actid:this.actid}).then(res=>{
					if(res.code ==0){
						this.activityText = res.data
						let {prize} = res.data
						console.log('1123',prize)
						let result = prize? prize.total-prize.be_left : 0
						
						let text = result+''
						text = text.split('')
						let length = 5 - text.length
						for(let i =0 ; i< length; i++){
							text.unshift(0)
						}
						if(prize){
							this.activityOtherData = {
								progress:(result / prize.total)*100,
								total:prize.total,
								be_left:prize.be_left,
								text:text
							}
						}else{
							this.activityOtherData = {
								progress: 0,
								total:  0,
								be_left: 0,
								text:text
							}
						}
						
						
						let _this = this
						this.showStatus = true
						setTimeout(()=>{
							_this.initCss()
						},300)
						if(res.data.has_task && this.taskMenuData.length==0){
							this.initTask()
						}
					}
				})
			},
			getWordData(){
				collectWord({actid:this.actid},'collect','collect').then(res=>{
 
					this.wordData = res.data.index_words
					this.wordLength = res.data.index_words.length
					let token = uni.getStorageSync(this.actid+'bearerToken') || null
					console.log('token',token)
					if(token!=null){
						this.getChance()
					}
					
 
				})
			},
			//计算当前次数
			sumChance(){
				let noFinish = 0
				console.log(this.taskMenuData)
				this.taskMenuData.forEach(item=>{
					if(item.is_finish==false){
							noFinish++
					}
				})
				if(noFinish>0){this.isMoreTask = true}
				else{this.isMoreTask = false}
			},
			getpreWord(){
					let callback=()=>{
						if(this.chance>0){
							this.getWord()
						}else{
							this.sumChance()
							if(this.activityText.has_task && this.taskMenuData.length>0 && this.isMoreTask){
								uni.showToast({ title:'集卡次数不足，做任务获取更多', icon:'none', duration:3000 })
								this.showTask = true
							}else{
								uni.showToast({ title:'已无未完成任务，请明日再来', icon:'none', duration:3000 })
							}
							return
						}
						
						
					}
					this.getAuth(callback)
			},
			getWord(val){
				this.getActivity()
				if(val==1){
					this.modalLott = false
					this.sumChance()
					if(this.activityText.has_task && this.taskMenuData.length>0 && this.isMoreTask){
						uni.showToast({ title:'集卡次数不足，做任务获取更多', icon:'none', duration:3000 })
						this.showTask = true
					}else{
						uni.showToast({ title:'已无未完成任务，请明日再来', icon:'none', duration:3000 })
					}
					return
				}
				collectLottery({actid:this.actid},'collect','collect').then(res=>{
					this.modalLott = true
					if(res.code==0){
						this.lottData = res.data	
						if(res.data.hasOwnProperty('prize')){
							if(res.data.prize.type==2){
								this.lottData.prize.image = this.qiniuUrl+'bag.png'
							}
							if(res.data.prize.type==3){
								this.lottData.prize.image = this.qiniuUrl+'prize_mt.png'
							}
							this.isFinishAnimation = false
							this.startFinishAnimation()
						}
						
						this.getWordData()
					}
				})
			},
			initTask(){
				taskList({actid:this.actid}).then(res=>{
					this.taskMenuData = res.data
				})
			},
			//被当做iframe引用时处理数据
			setIframeData(){
				let _this = this
				window.addEventListener('message',function(e){
 
					let data = e.data
					//强制兼容后台数据
					_this.frameData={ code:0, data:data }
					let {settings}=data
 
					_this.activityText={
						view_num:settings.view_num,
						play_num:settings.play_num,
						win_num:settings.win_num,
						winners:[{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'}]
					}
					
					let {popup} = data
					switch(popup){
						case 'win_popup':
							_this.serviceData = { id: 116, redid: 0, title: "示例奖品", type: 2, }
							_this.serviceData.win_popup = _this.setData.win_popup
							_this.modalData.show=true
							_this.modalData.type=2
							break;
						case 'closewin_popup':
							_this.modalData.show=false
							break;
						case "task_popup":
							_this.taskMenuData = frameJs.taskMenuData
							_this.showTask=true
							break;
						case "closetask_popup":
							_this.showTask=false
							break;
						default:break;
					}
					
					
					_this.activityOtherData = {
						progress:(10 / 20)*100,
						total:'20',
						be_left:'10',
						text:['0','0','0','1','0']
					}
					clearInterval(_this.timer)
					_this.wordData=[]
					for(let i=0;i<10;i++){
						let item = {image:require('../../../static/collect/word.png'),user_num:i}
						_this.wordData.push(item)
					}
					_this.chance='100(模拟)'
					_this.wordLength = 10
					_this.init()
					setTimeout(()=>{ _this.initCss() },100) },false);
			},
		},
	 	mounted() {
			if(!this.isframe){
				this.init()
				this.getWordData()
				this.getActivity()
				// console.log('初始化')
			}
			let code = uni.getStorageSync(this.actid+'Invite') || 0
			if(code != 0 ){
				this.showHelpModal = true
			}
			
 
		},
		created() {
			this.actid =uni.getStorageSync('actid')
			this.$store.commit('SETACTIVITYNAME','collect')
			let web  = uni.getStorageSync('WEB') || null
			if(web){
  
				this.showStatus = true
				this.isframe  = true
				this.actid = '123'
				this.setIframeData()
			}
		},
		watch:{},

	}
</script>

<style lang="scss" scoped>
	@import "./collectWord.scss";
	// @import "../animation.css";
	
</style>
